package com.api.demo.controller;

import com.api.demo.entity.User;
import com.api.demo.service.FollowService;
import com.api.demo.service.UserService;
import com.api.demo.util.JwtUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/follows")
public class FollowController {

    @Autowired
    private FollowService followService;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 关注用户
     */
    @PostMapping("/{followingId}")
    public ResponseEntity<?> follow(@RequestHeader("Authorization") String token,
            @PathVariable Long followingId) {
        // 验证token
        Long currentUserId = getUserIdFromToken(token);
        if (currentUserId == null) {
            return ResponseEntity.badRequest().body(new MessageResponse("无效的token"));
        }

        boolean success = followService.follow(currentUserId, followingId);
        if (success) {
            return ResponseEntity.ok(new MessageResponse("关注成功"));
        } else {
            return ResponseEntity.badRequest().body(new MessageResponse("关注失败"));
        }
    }

    /**
     * 获取我的粉丝列表（带分页）
     */
    @GetMapping("/followers")
    public ResponseEntity<?> getFollowers(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        // 验证token
        Long currentUserId = getUserIdFromToken(token);
        if (currentUserId == null) {
            return ResponseEntity.badRequest().body(new MessageResponse("无效的token"));
        }

        // 获取总粉丝数
        int totalFollowers = followService.getFollowersCount(currentUserId);

        // 计算分页参数
        int totalPages = (int) Math.ceil((double) totalFollowers / size);
        if (page < 1)
            page = 1;
        if (page > totalPages && totalPages > 0)
            page = totalPages;

        // 计算偏移量
        int offset = (page - 1) * size;

        // 获取当前页的粉丝列表
        List<User> followers = followService.getFollowersWithPagination(currentUserId, offset, size);
        List<UserInfoResponse> userInfoList = followers.stream()
                .map(this::convertToUserInfoResponse)
                .collect(Collectors.toList());

        // 构建分页响应
        Map<String, Object> response = new HashMap<>();
        response.put("total", totalFollowers);
        response.put("totalPages", totalPages);
        response.put("currentPage", page);
        response.put("pageSize", size);
        response.put("list", userInfoList);

        return ResponseEntity.ok(response);
    }

    @GetMapping("/following")
    public ResponseEntity<?> getFollowings(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        // 验证token
        Long currentUserId = getUserIdFromToken(token);
        if (currentUserId == null) {
            return ResponseEntity.badRequest().body(new MessageResponse("无效的token"));
        }

        // ✅ 修复1：获取总关注数（当前用户关注了多少人）
        int totalFollowing = followService.getFollowingCount(currentUserId);

        // 计算分页参数
        int totalPages = (int) Math.ceil((double) totalFollowing / size);
        if (page < 1)
            page = 1;
        if (page > totalPages && totalPages > 0)
            page = totalPages;

        int offset = (page - 1) * size;

        // ✅ 修复2：获取关注列表（当前用户关注的人）
        List<User> followings = followService.getFollowingWithPagination(currentUserId, offset, size);
        List<UserInfoResponse> userInfoList = followings.stream()
                .map(this::convertToUserInfoResponse)
                .collect(Collectors.toList());

        // 构建分页响应
        Map<String, Object> response = new HashMap<>();
        response.put("total", totalFollowing); // ✅ 修复3：总关注数
        response.put("totalPages", totalPages);
        response.put("currentPage", page);
        response.put("pageSize", size);
        response.put("list", userInfoList); // 关注列表数据

        return ResponseEntity.ok(response);
    }

    /**
     * 获取指定用户的关注数据
     */
    @GetMapping("/stats/{userId}")
    public ResponseEntity<?> getFollowStats(@PathVariable Long userId) {
        // 检查用户是否存在
        User user = userService.getById(userId);
        if (user == null) {
            return ResponseEntity.badRequest().body(new MessageResponse("用户不存在"));
        }

        Map<String, Object> stats = new HashMap<>();
        stats.put("followingCount", followService.getFollowingCount(userId));
        stats.put("followersCount", followService.getFollowersCount(userId));

        return ResponseEntity.ok(stats);
    }

    @DeleteMapping("/{followingId}")
    public ResponseEntity<?> deleteFollow(@RequestHeader("Authorization") String token,
            @PathVariable Long followingId) {
        Long currentUserId = getUserIdFromToken(token);

        followService.notFollow(currentUserId, followingId);
        return ResponseEntity.ok("取关成功");
    }

    /**
     * 从token中获取用户ID
     */
    private Long getUserIdFromToken(String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        if (!jwtUtil.validateToken(token)) {
            return null;
        }

        return jwtUtil.getUserIdFromToken(token);
    }

    /**
     * 将User对象转换为UserInfoResponse
     */
    private UserInfoResponse convertToUserInfoResponse(User user) {
        UserInfoResponse response = new UserInfoResponse();
        response.setId(user.getId());
        response.setUsername(user.getUsername());
        response.setAvatar(user.getAvatar());
        return response;
    }

    @Data
    public static class MessageResponse {
        private String message;

        public MessageResponse(String message) {
            this.message = message;
        }
    }

    @Data
    public static class UserInfoResponse {
        private Long id;
        private String username;
        private String avatar;
    }
}